<template>
  <!-- 批量导入模态框 -->
  <n-modal v-model:show="showModal" :mask-closable="false">
    <n-card 
      style="width: 90%; max-width: 1200px" 
      title="批量导入党员信息" 
      :bordered="false"
      size="huge"
      role="dialog"
      aria-modal="true"
    >
      <template #header-extra>
        <n-button quaternary circle @click="handleClose">
          <template #icon>
            <n-icon><CloseIcon /></n-icon>
          </template>
        </n-button>
      </template>

      <n-steps :current="currentStep" :status="stepStatus">
        <n-step title="选择字段" />
        <n-step title="上传文件" />
        <n-step title="数据预览" />
        <n-step title="确认导入" />
      </n-steps>

      <div class="mt-6">
        <!-- 步骤1: 选择字段 -->
        <div v-if="currentStep === 1">
          <n-space vertical size="large">
            <n-alert type="info" title="导入说明">
              请先选择要批量更新的字段，然后下载模板并填写数据。Excel文件应包含：姓名、学号、以及选定的字段值。
            </n-alert>
            
            <n-form label-placement="left" label-width="120">
              <n-form-item label="选择更新字段">
                <n-select
                  v-model:value="selectedUpdateField"
                  :options="updateFieldOptions"
                  placeholder="请选择要更新的字段"
                  style="width: 300px"
                />
              </n-form-item>
            </n-form>

            <n-space>
              <n-button 
                type="primary" 
                @click="downloadTemplate" 
                :disabled="!selectedUpdateField"
                :loading="templateDownloading"
              >
                <template #icon><n-icon><DownloadIcon /></n-icon></template>
                下载Excel模板
              </n-button>
              
              <n-button 
                type="success" 
                @click="currentStep = 2" 
                :disabled="!selectedUpdateField"
              >
                下一步：上传文件
              </n-button>
            </n-space>
          </n-space>
        </div>

        <!-- 步骤2: 上传文件 -->
        <div v-if="currentStep === 2">
          <n-space vertical size="large">
            <n-alert type="info" title="上传要求">
              请上传填写完成的Excel文件。文件格式要求：.xlsx 或 .xls，大小不超过5MB。
            </n-alert>

            <n-upload
              ref="uploadRef"
              :file-list="fileList"
              :max="1"
              accept=".xlsx,.xls"
              :on-before-upload="beforeUpload"
              :on-change="handleFileChange"
              :custom-request="customRequest"
              :show-file-list="true"
              drag
            >
              <n-upload-dragger>
                <div style="margin-bottom: 12px">
                  <n-icon size="48" :depth="3">
                    <FileUploadIcon />
                  </n-icon>
                </div>
                <n-text style="font-size: 16px">
                  点击或者拖动文件到该区域来上传
                </n-text>
                <n-p depth="3" style="margin: 8px 0 0 0">
                  支持 .xlsx 和 .xls 格式，文件大小不超过 5MB
                </n-p>
              </n-upload-dragger>
            </n-upload>

            <n-space>
              <n-button @click="currentStep = 1">上一步</n-button>
              <n-button 
                type="primary" 
                @click="parseExcelFile" 
                :disabled="!uploadedFile"
                :loading="parsing"
              >
                解析文件
              </n-button>
            </n-space>
          </n-space>
        </div>

        <!-- 步骤3: 数据预览 -->
        <div v-if="currentStep === 3">
          <n-space vertical size="large">
            <n-alert 
              :type="hasErrors ? 'warning' : 'success'" 
              :title="hasErrors ? '数据验证警告' : '数据验证通过'"
            >
              <template v-if="hasErrors">
                检测到 {{ errorCount }} 条数据存在问题，请修正后再导入。红色标记的字段需要修正。
              </template>
              <template v-else>
                所有数据验证通过，可以进行导入操作。
              </template>
            </n-alert>

            <n-data-table
              :columns="previewColumns"
              :data="previewData"
              :pagination="{ pageSize: 10 }"
              :max-height="400"
              striped
              :row-class-name="getRowClassName"
            />

            <n-space>
              <n-button @click="currentStep = 2">上一步</n-button>
              <n-button 
                type="primary" 
                @click="currentStep = 4" 
                :disabled="hasErrors"
              >
                下一步：确认导入
              </n-button>
            </n-space>
          </n-space>
        </div>

        <!-- 步骤4: 确认导入 -->
        <div v-if="currentStep === 4">
          <n-space vertical size="large">
            <n-alert type="success" title="准备导入">
              即将导入 {{ validDataCount }} 条数据，更新字段：{{ getFieldLabel(selectedUpdateField) }}
            </n-alert>

            <!-- 修正统计组件 -->
            <div class="statistic-container">
              <n-statistic label="待导入数据" :value="validDataCount" />
              <n-statistic label="更新字段" :value="getFieldLabel(selectedUpdateField)" />
              <n-statistic label="预计用时" value="约30秒" />
            </div>

            <n-space>
              <n-button @click="currentStep = 3">上一步</n-button>
              <n-button 
                type="primary" 
                @click="executeBatchImport" 
                :loading="importing"
                size="large"
              >
                <template #icon><n-icon><CheckIcon /></n-icon></template>
                确认导入
              </n-button>
            </n-space>
          </n-space>
        </div>
      </div>

      <template #footer>
        <n-space justify="end">
          <n-button @click="handleClose">取消</n-button>
        </n-space>
      </template>
    </n-card>
  </n-modal>

  <!-- 导入结果模态框 -->
  <n-modal v-model:show="showResultModal" :mask-closable="false">
    <n-card 
      style="width: 600px" 
      title="导入结果" 
      :bordered="false"
      size="huge"
      role="dialog"
      aria-modal="true"
    >
      <template #header-extra>
        <n-button quaternary circle @click="showResultModal = false">
          <template #icon>
            <n-icon><CloseIcon /></n-icon>
          </template>
        </n-button>
      </template>

      <n-result 
        :status="importResult.success ? 'success' : 'error'"
        :title="importResult.success ? '导入成功' : '导入失败'"
        :description="importResult.message"
      >
        <template #footer>
          <n-space justify="center">
            <div class="result-statistic-container" v-if="importResult.success">
              <n-statistic label="成功导入" :value="importResult.successCount" />
              <n-statistic label="失败条数" :value="importResult.failCount" />
              <n-statistic label="总计处理" :value="importResult.totalCount" />
            </div>
          </n-space>
        </template>
      </n-result>

      <template #footer>
        <n-space justify="end">
          <n-button type="primary" @click="handleImportComplete">
            确定
          </n-button>
        </n-space>
      </template>
    </n-card>
  </n-modal>
</template>

<script setup>
import { ref, h, computed } from 'vue'
import {
  NModal, NCard, NSteps, NStep, NAlert, NForm, NFormItem, NSelect,
  NSpace, NButton, NIcon, NUpload, NUploadDragger, NText, NP,
  NDataTable, NResult, NStatistic, NTag, NInput, useDialog, useMessage
} from 'naive-ui'
import {
  X as CloseIcon,
  FileUpload as FileUploadIcon,
  Download as DownloadIcon,
  Check as CheckIcon
} from '@vicons/tabler'
import * as XLSX from 'xlsx'

// Props
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:show', 'import-success'])

// 创建对话框和消息实例
const dialog = useDialog()
const message = useMessage()

// 响应式数据
const showModal = computed({
  get: () => props.show,
  set: (value) => emit('update:show', value)
})

const showResultModal = ref(false)
const currentStep = ref(1)
const stepStatus = ref('process')
const selectedUpdateField = ref('')
const templateDownloading = ref(false)
const fileList = ref([])
const uploadedFile = ref(null)
const parsing = ref(false)
const previewData = ref([])
const importing = ref(false)
const importResult = ref({
  success: false,
  message: '',
  successCount: 0,
  failCount: 0,
  totalCount: 0
})

// 可更新字段选项
const updateFieldOptions = [
  { label: '入党申请书时间', value: 'applicationDate' },
  { label: '谈心谈话时间', value: 'heartToHeartTalkDate' },
  { label: '列为积极分子时间', value: 'activistDesignationDate' },
  { label: '群众意见时间', value: 'massOpinionDate' },
  { label: '自传时间', value: 'autobiographyDate' },
  { label: '接收预备党员时间', value: 'probationaryAcceptanceDate' },
  { label: '转正时间', value: 'conversionDate' }
]

// 计算属性
const hasErrors = computed(() => {
  return previewData.value.some(row => row._hasError)
})

const errorCount = computed(() => {
  return previewData.value.filter(row => row._hasError).length
})

const validDataCount = computed(() => {
  return previewData.value.filter(row => !row._hasError).length
})

const previewColumns = computed(() => {
  const fieldLabel = getFieldLabel(selectedUpdateField.value)
  return [
    {
      title: '序号',
      key: 'index',
      width: 60,
      render: (row, index) => index + 1
    },
    {
      title: '姓名',
      key: 'memberName',
      width: 100,
      render: (row) => {
        return h('span', {
          class: row._errors?.memberName ? 'text-red-500' : ''
        }, row.memberName || '')
      }
    },
    {
      title: '学号',
      key: 'studentId',
      width: 120,
      render: (row) => {
        return h('span', {
          class: row._errors?.studentId ? 'text-red-500' : ''
        }, row.studentId || '')
      }
    },
    {
      title: fieldLabel,
      key: selectedUpdateField.value,
      width: 150,
      render: (row) => {
        const value = row[selectedUpdateField.value]
        return h('span', {
          class: row._errors?.[selectedUpdateField.value] ? 'text-red-500' : ''
        }, value || '')
      }
    },
    {
      title: '验证状态',
      key: 'status',
      width: 100,
      render: (row) => {
        if (row._hasError) {
          return h(NTag, { type: 'error', size: 'small' }, { default: () => '有错误' })
        }
        return h(NTag, { type: 'success', size: 'small' }, { default: () => '验证通过' })
      }
    },
    {
      title: '错误信息',
      key: 'errorMessage',
      width: 200,
      render: (row) => {
        if (row._errorMessages && row._errorMessages.length > 0) {
          return h('div', { class: 'text-red-500 text-sm' }, row._errorMessages.join('; '))
        }
        return '-'
      }
    },
    {
      title: '操作',
      key: 'actions',
      width: 100,
      render: (row, index) => {
        return h(NButton, {
          size: 'small',
          type: 'primary',
          disabled: !row._hasError,
          onClick: () => editRow(index)
        }, { default: () => '修正' })
      }
    }
  ]
})

// 工具函数
const getFieldLabel = (fieldKey) => {
  const option = updateFieldOptions.find(opt => opt.value === fieldKey)
  return option?.label || fieldKey
}

const getRowClassName = (row) => {
  return row._hasError ? 'error-row' : ''
}

// 主要功能函数
const downloadTemplate = async () => {
  templateDownloading.value = true
  try {
    const fieldLabel = getFieldLabel(selectedUpdateField.value)
    
    // 创建模板数据
    const templateData = [
      {
        '姓名': '张三',
        '学号': '2021001001',
        [fieldLabel]: '2023-03-15'
      },
      {
        '姓名': '李四',
        '学号': '2021001002',
        [fieldLabel]: '2023-03-16'
      }
    ]

    // 创建工作簿
    const wb = XLSX.utils.book_new()
    const ws = XLSX.utils.json_to_sheet(templateData)
    
    // 设置列宽
    ws['!cols'] = [
      { width: 15 },
      { width: 15 },
      { width: 20 }
    ]
    
    XLSX.utils.book_append_sheet(wb, ws, '模板数据')
    
    // 下载文件
    XLSX.writeFile(wb, `党员信息批量导入模板_${fieldLabel}.xlsx`)
    
    message.success('模板下载成功')
  } catch (error) {
    console.error('下载模板失败:', error)
    message.error('下载模板失败')
  } finally {
    templateDownloading.value = false
  }
}

const beforeUpload = (data) => {
  const file = data.file.file
  const isValidType = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                      file.type === 'application/vnd.ms-excel'
  
  if (!isValidType) {
    message.error('只能上传 Excel 文件')
    return false
  }
  
  const isValidSize = file.size / 1024 / 1024 < 5
  if (!isValidSize) {
    message.error('文件大小不能超过 5MB')
    return false
  }
  
  return true
}

const handleFileChange = (data) => {
  fileList.value = data.fileList
  if (data.fileList.length > 0) {
    uploadedFile.value = data.fileList[0].file
  } else {
    uploadedFile.value = null
  }
}

const customRequest = ({ file, onFinish, onError }) => {
  uploadedFile.value = file
  onFinish()
}

const parseExcelFile = async () => {
  if (!uploadedFile.value) {
    message.error('请先上传文件')
    return
  }
  
  parsing.value = true
  try {
    const arrayBuffer = await uploadedFile.value.arrayBuffer()
    const workbook = XLSX.read(arrayBuffer, { type: 'array' })
    const sheetName = workbook.SheetNames[0]
    const worksheet = workbook.Sheets[sheetName]
    const jsonData = XLSX.utils.sheet_to_json(worksheet)
    
    if (jsonData.length === 0) {
      message.error('Excel文件中没有数据')
      return
    }
    
    // 验证和处理数据
    const fieldLabel = getFieldLabel(selectedUpdateField.value)
    const processedData = jsonData.map((row, index) => {
      const processedRow = {
        memberName: row['姓名'] || '',
        studentId: row['学号'] || '',
        [selectedUpdateField.value]: row[fieldLabel] || '',
        _hasError: false,
        _errors: {},
        _errorMessages: []
      }
      
      // 验证数据
      validateRow(processedRow)
      
      return processedRow
    })
    
    previewData.value = processedData
    currentStep.value = 3
    message.success(`解析完成，共 ${processedData.length} 条数据`)
    
  } catch (error) {
    console.error('解析Excel文件失败:', error)
    message.error('解析文件失败，请检查文件格式')
  } finally {
    parsing.value = false
  }
}

const validateRow = (row) => {
  const errors = {}
  const errorMessages = []
  
  // 验证姓名
  if (!row.memberName || row.memberName.trim() === '') {
    errors.memberName = true
    errorMessages.push('姓名不能为空')
  }
  
  // 验证学号
  if (!row.studentId || row.studentId.trim() === '') {
    errors.studentId = true
    errorMessages.push('学号不能为空')
  } else if (!/^[A-Za-z0-9]+$/.test(row.studentId)) {
    errors.studentId = true
    errorMessages.push('学号格式不正确')
  }
  
  // 验证日期字段
  const dateValue = row[selectedUpdateField.value]
  if (!dateValue || dateValue.trim() === '') {
    errors[selectedUpdateField.value] = true
    errorMessages.push(`${getFieldLabel(selectedUpdateField.value)}不能为空`)
  } else {
    // 简单的日期格式验证
    const dateRegex = /^\d{4}-\d{2}-\d{2}$/
    if (!dateRegex.test(dateValue)) {
      errors[selectedUpdateField.value] = true
      errorMessages.push(`${getFieldLabel(selectedUpdateField.value)}格式应为 YYYY-MM-DD`)
    }
  }
  
  row._errors = errors
  row._errorMessages = errorMessages
  row._hasError = Object.keys(errors).length > 0
}

const editRow = (index) => {
  const row = previewData.value[index]
  
  dialog.create({
    title: '修正数据',
    content: () => {
      const formData = ref({
        memberName: row.memberName,
        studentId: row.studentId,
        [selectedUpdateField.value]: row[selectedUpdateField.value]
      })
      
      return h('div', [
        h('div', { style: 'margin-bottom: 16px' }, [
          h('label', '姓名：'),
          h(NInput, {
            value: formData.value.memberName,
            onUpdateValue: (val) => formData.value.memberName = val
          })
        ]),
        h('div', { style: 'margin-bottom: 16px' }, [
          h('label', '学号：'),
          h(NInput, {
            value: formData.value.studentId,
            onUpdateValue: (val) => formData.value.studentId = val
          })
        ]),
        h('div', { style: 'margin-bottom: 16px' }, [
          h('label', `${getFieldLabel(selectedUpdateField.value)}：`),
          h(NInput, {
            value: formData.value[selectedUpdateField.value],
            onUpdateValue: (val) => formData.value[selectedUpdateField.value] = val,
            placeholder: 'YYYY-MM-DD'
          })
        ])
      ])
    },
    positiveText: '保存',
    negativeText: '取消',
    onPositiveClick: () => {
      // 更新数据并重新验证
      Object.assign(row, formData.value)
      validateRow(row)
      previewData.value[index] = { ...row }
      message.success('数据已更新')
    }
  })
}

const executeBatchImport = async () => {
  importing.value = true
  try {
    // 模拟批量导入API调用
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    const validData = previewData.value.filter(row => !row._hasError)
    const result = await batchImportApi(validData, selectedUpdateField.value)
    
    importResult.value = result
    showResultModal.value = true
    
  } catch (error) {
    console.error('批量导入失败:', error)
    importResult.value = {
      success: false,
      message: error.message || '导入失败',
      successCount: 0,
      failCount: validDataCount.value,
      totalCount: validDataCount.value
    }
    showResultModal.value = true
  } finally {
    importing.value = false
  }
}

const batchImportApi = async (data, fieldKey) => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    // 模拟一些导入失败的情况
    const successCount = Math.floor(data.length * 0.9) // 90% 成功率
    const failCount = data.length - successCount
    
    return {
      success: true,
      message: `批量导入完成`,
      successCount,
      failCount,
      totalCount: data.length
    }
  } catch (error) {
    throw new Error('批量导入接口调用失败')
  }
}

const handleImportComplete = () => {
  showResultModal.value = false
  handleClose()
  if (importResult.value.success) {
    emit('import-success') // 通知父组件刷新数据
  }
}

const handleClose = () => {
  showModal.value = false
  // 重置状态
  currentStep.value = 1
  selectedUpdateField.value = ''
  fileList.value = []
  uploadedFile.value = null
  previewData.value = []
  stepStatus.value = 'process'
}
</script>

<style scoped>
/* 红色文本样式 */
.text-red-500 {
  color: #ef4444;
}

/* 统计容器样式 */
.statistic-container {
  display: flex;
  gap: 24px;
  justify-content: center;
  padding: 16px;
  background-color: #f8fafc;
  border-radius: 8px;
}

.result-statistic-container {
  display: flex;
  gap: 24px;
  justify-content: center;
}

/* 预览表格错误行样式 */
:deep(.error-row) {
  background-color: #fef2f2;
}

:deep(.error-row:hover) {
  background-color: #fee2e2;
}

/* 步骤条样式优化 */
:deep(.n-steps) {
  margin-bottom: 24px;
}

/* 上传区域样式优化 */
:deep(.n-upload-dragger) {
  border: 2px dashed #d1d5db;
  border-radius: 8px;
  background-color: #fafafa;
  transition: all 0.3s ease;
}

:deep(.n-upload-dragger:hover) {
  border-color: #18a058;
  background-color: #f0f9ff;
}
</style>